<template>
	<div style="background-color: white;">
		<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
			<el-tab-pane label="房屋费用及关联费用汇总" name="first"></el-tab-pane>
		</el-tabs>
	</div>

	<div v-if="activeName === 'first'" class="fir">
		<div class="f-but">
			<el-button class="f-but1" @click="dialogVisible = true">高级筛选</el-button>
			<el-dialog v-model="dialogVisible">
				<div class="f-dia">
					<div class="f-dia-top">
						<form>
							<el-form-item label="所属房屋" style="width:300px;margin-right: 10px;margin-bottom: 50px;">
								<el-cascader v-model="lastNumber.xz" :options="options" :props="props1" clearable />
							</el-form-item>
						</form>
					</div>
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="dialogVisible = false">取消</el-button>
						<el-button type="primary" @click="loadExpense(); dialogVisible = false">
							确定
						</el-button>
					</div>
				</template>
			</el-dialog>
			<el-button @click="exportExcel" type="primary" class="f-but2"
				style="width:70px;top:0;">全部导出</el-button>
		</div>
		<div>
			<el-table :data="data.expense" style="width: 100%">
				<el-table-column label="房屋信息" width="200">
					<template #default="scope">
						{{ scope.row.buildingName }}/{{scope.row.unitName}}/{{scope.row.houseNumber}}
					</template>
				</el-table-column>
				 <el-table-column label="费用名称" min-width="200">  
  <template #default="scope">  
    <div>  
      <span v-for="(itemName, index) in scope.row.billingItemsName.split(',')" :key="index">  
        {{ itemName.trim() }}  
        <!-- 如果需要分隔符，可以在这里添加，比如逗号加空格 -->  
        {{ index < scope.row.billingItemsName.split(',').length - 1 ? ', ' : '' }}  
      </span>  
    </div>  
  </template>  
</el-table-column>
				<el-table-column label="费用">
					<template #default="scope">
						{{ scope.row.fyje }}
					</template>
				</el-table-column>
				<el-table-column label="费用起止月">
					<template #default="scope">
						{{ scope.row.fyqzTime }}
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="总计" width="200">
					<el-table-column label="费用总计" prop="totalFee" width="100">
					</el-table-column>
				</el-table-column>
			</el-table>

			<div class="demo-pagination-block" style="display: flex;">
				<el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
					:page-sizes="[5, 15, 25, 35]" :size="size" :disabled="disabled" :background="background"
					layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
				<div style="margin-left: 910px;">{{totalFee}}</div>
			</div>
		</div>


	</div>

</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted, computed } from 'vue'
	import type { TabsPaneContext, ElMessageBox } from 'element-plus'
	import $http from '../router/AxiosApi';
	import type {
		ComponentSize
	} from 'element-plus'
	
	import * as XLSX from "xlsx";
	const activeName = ref('first')
	const dialogVisible = ref(false)
	const value3 = ref('')
	const value4 = ref('')
	const value5 = ref('')
	const value6 = ref('')
	const currentPage4 = ref(0)
	const pageSize4 = ref(0)
	const size = ref<ComponentSize>('default')
	const page = ref(1)
	const pageSize = ref(5)
	const total = ref(0)
	const background = ref(false)
	const disabled = ref(false)
	const handleClick = (tab : TabsPaneContext, event : Event) => {
		console.log(tab, event)
	}
	const data = reactive({
		expense: [],
		house: [],
		item: []
	})
	const props1 = {
		checkStrictly: true,
	}
	const handleSizeChange = (val : number) => {
		pageSize.value = val;
		loadExpense(page, pageSize);
	}
	const handleCurrentChange = (val : number) => {
		page.value = val;
		loadExpense(page, pageSize);
	}
	const form = reactive({
		houseId: '',
		unitId: '',
		buildingId: '',
		regionId: '',
		billingItemsName: ''
	})

	const totalFee = computed(() => {
		return data.expense.reduce((sum, item) => sum + (item.fyje || 0), 0);
	});
	const options = reactive([]);
	const lastNumber = reactive({
		xz: ''
	})
	onMounted(() => {
		loadExpense()
		loadAll()
		loadItem()
	})
	const loadExpense = () => {
		console.log(lastNumber.xz)
		if (lastNumber.xz === undefined) {
			console.log("未选择");
			form.buildingId = ''
			form.houseId = ''
			form.regionId = ''
			form.unitId = ''
		} else {
			form.regionId = lastNumber.xz[0]; // 第一个选项作为 regionId
			if (lastNumber.xz.length >= 2) {
				form.buildingId = lastNumber.xz[1]; // 第二个选项作为 buildingId
			}
			if (lastNumber.xz.length >= 3) {
				form.unitId = lastNumber.xz[2]; // 第三个选项作为 unitId
			}
			if (lastNumber.xz.length >= 4) {
				form.houseId = lastNumber.xz[3]; // 第四个选项作为 houseId
			}
		}
		$http.post(`selectAllExpense?currentPage=${page.value}&pageSize=${pageSize.value}`, form).then((res) => {
			console.log(res.data)
			data.expense = res.data.data.list
			total.value = res.data.data.total
			currentPage4.value = res.data.data.pageNum
			pageSize4.value = res.data.data.pageSize
		})
	}
	const loadAll = () => {
	    $http.post("findAll").then((res) => {
	        const data = res.data;
	        if (data && data.length > 0) {
	            // 使用 Map 来去重并组织数据
	            const regionsMap = new Map();
	
	            data.forEach(item => {
	                if (!regionsMap.has(item.regionId)) {
	                    regionsMap.set(item.regionId, {
	                        value: item.regionId,
	                        label: item.regionName,
	                        children: []
	                    });
	                }
	                
	                const region = regionsMap.get(item.regionId);
	
	                let building = region.children.find(b => b.value === item.buildingId);
	                if (!building) {
	                    building = {
	                        value: item.buildingId,
	                        label: item.buildingName,
	                        children: []
	                    };
	                    region.children.push(building);
	                }
	
	                let unit = building.children.find(u => u.value === item.unitId);
	                if (!unit) {
	                    unit = {
	                        value: item.unitId,
	                        label: item.unitName,
	                        children: []
	                    };
	                    building.children.push(unit);
	                }
	
	                unit.children.push({
	                    value: item.houseId,
	                    label: item.houseNumber
	                });
	            });
	
	            // 将 Map 转换为数组
	            const regionsArray = Array.from(regionsMap.values());
	
	            // 更新 options 数组
	            options.splice(0, options.length, ...regionsArray);
	        }
	    });
	};
	
	const loadItem = () => {
		$http.post("findItem").then((res) => {
			data.item = res.data
			console.log(res.data)
		})
	}
	//导出
	const exportExcel=()=>{
	  let tableData2 = [
	    ['房屋信息', '费用名称', '费用', '费用起止月','费用总计']//导出表头
	  ] // 表格表头
	   let totalCost = 0; // 初始化总费用
	  data.expense.forEach((item, index) => {
	    let rowData = []
	    //导出内容的字段
	    rowData = [
	      item.buildingName+"/"+item.unitName+"/"+item.houseNumber,
	      item.billingItemsName,
		  item.fyje,
	      item.fyqzTime
	    ]
		 
		    totalCost += parseFloat(item.fyje);
			rowData.push(totalCost)
			tableData2.push(rowData);
	  })
	  // 计算每列的最大宽度
	  const wscols = calculateColumnWidths(tableData2);
	
	  let workSheet = XLSX.utils.aoa_to_sheet(tableData2);
	  let bookNew = XLSX.utils.book_new();
	  // 设置自适应列宽度
	  workSheet['!cols'] = wscols;
	
	  XLSX.utils.book_append_sheet(bookNew, workSheet, '房屋报表数据') // 工作簿名称
	  let name = '房屋报表数据' + '.xlsx'
	  XLSX.writeFile(bookNew, name) // 保存的文件名
	}
	
	//设置列宽
	const calculateColumnWidths=(data)=>{
	  const wscols=[]
	
	  // 初始化列宽
	  for (let i = 0; i < data[0].length; i++) {
	    wscols.push({ wch: 10 }); // 初始宽度，可以根据实际需要设置
	  }
	
	  // 遍历数据，找出每列中最大的字符长度
	  for (let r = 0; r < data.length; r++) {
	    for (let c = 0; c < data[r].length; c++) {
	      const cellContent = data[r][c] !== null && data[r][c] !== undefined ? data[r][c].toString() : '';
	      const cellLength = getCellTextWidth(cellContent);
	
	      // 更新该列的最大宽度
	      if (!wscols[c] || cellLength > wscols[c].wch) {
	        wscols[c] = { wch: cellLength };
	      }
	    }
	  }
	
	  return wscols;
	}
	
	const  getCellTextWidth=(text)=>{
	  // 计算文本的宽度，可以根据需要调整计算方法
	  // 这里简单地使用字符串的长度作为宽度，可以根据实际情况优化
	  return text.length;
	}
</script>

<style scoped>
	.fir {
		background-color: white;
	}

	.f-but {
		display: flex;
		justify-content: end;
		margin-top: 20px;
		margin-bottom: 20px;
		height: 40px;
	}

	.f-but1 {
		padding: 10px 15px;
		border-radius: 5px;
		background-color: #fff;
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		color: black;
	}

	.f-but2 {
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		padding: 0 20px;
		color: #fff;
		background-color: #00c36d;
		border-color: #00c36d;
		margin-left: 20px;

	}

	.el-dialog {
		margin-top: 15vh;
		border-radius: 10px;
		padding: 30px;
		overflow: hidden;
	}

	.s-top {
		background-color: white;
		border-radius: 10px;
		padding: 20px;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	.s-xz {
		float: left;
		margin-right: 30px;
	}

	.s-but1 {
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		padding: 0px 20px;
		color: #7e8081;
		background-color: #fafafa;
		border: none;
	}

	.s-but2 {
		margin-left: 10px;
		min-width: 100px;
		height: 40px;
		font-size: 14px;
		padding: 0 20px;
		background-color: #00c36d;
		border-color: #00c36d;
		color: #fafafa;
	}

	.s-two {
		padding: 10px;
		background-color: white;
		margin-top: 10px;
		border-radius: 10px;
		text-align: left;
	}

	.t-top {
		background-color: white;
		border-radius: 10px;
		padding: 20px;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	.t-two {
		padding: 10px;
		background-color: white;
		margin-top: 10px;
		border-radius: 10px;
		text-align: left;
	}

	thead {
		position: sticky;
		top: 0;
		background-color: white;
		/* 可选：设置背景颜色以覆盖默认样式 */
		z-index: 100;
		/* 可选：确保thead在页面上方 */
	}

	table {
		width: 100%;
		/* 确保表格宽度占据整个父容器 */
		border-collapse: collapse;
		/* 合并边框 */
	}

	th,
	td {
		padding: 8px;
		/* 可选：设置单元格内边距 */
		border: 1px solid black;
		/* 设置边框样式 */
	}

	th:nth-child(2) {
		width: 2000px;
		/* 第二列的宽度 */
	}
</style>